<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title><!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Graph Drawing with Canvas</title>
  <style>
      canvas {
          border: 1px solid #000;
      }
  </style>
</head>
<body>

<canvas id="graphCanvas" width="400" height="400"></canvas>

<script>
  class Graph {
    constructor() {
      this.vertices = [];
      this.edges = {};
    }

    // 添加节点
    addVertex(vertex) {
      this.vertices.push(vertex);
      this.edges[vertex] = [];
    }

    // 添加边
    addEdge(vertex1, vertex2) {
      this.edges[vertex1].push(vertex2);
      // 如果是无向图，还需要添加反向的边
      // this.edges[vertex2].push(vertex1);
    }


    // 添加一个方法，用于获取节点的坐标
    getVertexCoordinates(vertex) {
      const index = this.vertices.indexOf(vertex);
      const radius = 20; // 节点的半径
      const angle = (index / this.vertices.length) * (2 * Math.PI);
      const x = 200 + 150 * Math.cos(angle);
      const y = 200 + 150 * Math.sin(angle);
      return { x, y };
    }

    // 添加一个方法，用于绘制图形
    drawGraph() {
      const canvas = document.getElementById('graphCanvas');
      const ctx = canvas.getContext('2d');

      ctx.clearRect(0, 0, canvas.width, canvas.height);

      for (const vertex of this.vertices) {
        const { x, y } = this.getVertexCoordinates(vertex);

        // 绘制节点
        ctx.beginPath();
        ctx.arc(x, y, 20, 0, 2 * Math.PI);
        ctx.fillStyle = '#66ccff';
        ctx.fill();
        ctx.stroke();
        ctx.closePath();

        // 绘制节点标签
        ctx.font = '12px Arial';
        ctx.fillStyle = '#000';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(vertex, x, y);
      }

      // 绘制边
      for (const vertex of this.vertices) {
        const { x: x1, y: y1 } = this.getVertexCoordinates(vertex);

        for (const neighbor of this.edges[vertex]) {
          const { x: x2, y: y2 } = this.getVertexCoordinates(neighbor);

          // 绘制边
          ctx.beginPath();
          ctx.moveTo(x1, y1);
          ctx.lineTo(x2, y2);
          ctx.strokeStyle = '#000';
          ctx.stroke();
          ctx.closePath();
        }
      }
    }
  }

  // 使用示例
  const myGraph = new Graph();

  myGraph.addVertex('A');
  myGraph.addVertex('B');
  myGraph.addVertex('C');
  myGraph.addVertex('D');
  myGraph.addVertex('E');

  myGraph.addEdge('A', 'B');
  myGraph.addEdge('B', 'C');
  myGraph.addEdge('B', 'D');
  myGraph.addEdge('C', 'E');

  myGraph.drawGraph();
</script>

</body>
</html>
</title>
</head>
<body>

</body>
</html>
